import re, os, sys

from liwe.module import LiweModule
from liwe.tree import Tree

class Docs ( LiweModule ):
	def __init__ ( self, liwe ):
		super ( Docs, self ).__init__ ( liwe, "docs" )

		self.dbm = self.liwe.dbm
	
		# Istanza del Tree per la manipolazione dell'albero
		self.tree = Tree ( liwe )

		self._re_mktree = re.compile ( r"(,|\.|-|!|\?|:)" )


	def add_node ( self, id_node, title, text, parent_id ):
		uid = self.pyhp.session.data.get ( "uid", -1 )

		dct = { "uid" : uid,
			"title" : title,
			"body" : text,
			"created" : "*NOW()" }

		if int ( id_node ):
			self.dbm.update ( "docs_node", dct, "id = %s" % id_node )
			nid = self.tree.search_node_id ( "docs", id_node )
			if nid: self.tree.change_attrs ( nid, { "text" : title } )
		else:
			self.dbm.insert ( "docs_node", dct )
			doc_id = self.dbm.insert_id ()
			nid = self.tree.add_node ( uid, "docs", title, doc_id, False, id_parent = parent_id )

		return { "res" : "OK" }

	def del_node ( self, id_node ):
		if not id_node: 
			return
		
		section = 'docs'
		node_lst = id_node.split ( '|' )
		success = 'false'

		for id in node_lst:
			self.dbm.delete ( "docs_node", "id = %s" % id ) 
			nid = self.tree.search_node_id ( "docs", id )
			if nid:
				self.tree.del_node_by_val ( section, id )

	def move_node ( self, evt_name = '', id_node = '' ):
		if not id_node:
			return
		section = 'docs'
		if evt_name == 'node_up':
			self.tree.node_up ( section, id_node )	
		if evt_name == 'node_down':
			self.tree.node_down ( section, id_node )	
	
	def get_node ( self, id_node ):
		vals = self.dbm.single_row ( "docs_node", [ 'title', 'body' ], "id = %s" % id_node );
		return vals

	def dump_tree ( self, section, parent_id ):
		return self.tree.get_subtree ( section, parent_id, 'docs_node', 'id',  [ 'title' ] );

	def dump_node ( self, title, parent_id ):
		return { "title": title, "parent_id": parent_id }

	def dump_html_tree ( self, section ):
		def mk_tree ( rs, level ):
			res = ''
			for rec in rs:
				rec [ '_tabs' ] = "&nbsp;&nbsp;" * level
				#rec [ '_txt' ] = rec [ 'text' ].replace ( " ", "-" )
				rec [ '_txt' ] = self._re_mktree.sub ( "", rec [ 'text' ] ).replace ( " ", "-" )

				res += '%(_tabs)s<a href="/docs/node/%(val)s/%(_txt)s">%(text)s</a><br />' % rec
				if 'nodes' in rec:
					res += mk_tree ( rec [ 'nodes' ], level + 1 )

			return res

		res = mk_tree ( self.tree.get_all_tree ( section, 0 ), 0 )

		return res

	def print_node ( self, mode, default_node ):
		node_id = default_node

		if mode == "session":
			node_id = self.pyhp.session.data.get ( "_docs_node_id", default_node )

		vals = self.dbm.single_row ( "docs_node", [ 'title', 'body' ], "id = %s" % node_id )
		if vals:
			self.data [ 'title' ] = vals [ 'title' ]
			return vals

		return "TEST"

	def search ( self, txt ):
		res = { "rows" : None }

		cur = self.dbm.select ( 'docs_node', [ 'id', 'title', 'body' ], "body LIKE '%%%s%%'" % txt, extras = "LIMIT 50" )

		if not cur: return res

		rows = []
		res [ "rows" ] = rows
		for row in cur:
			rows.append ( { "id" : row [ 'id' ],
					"title" : row [ 'title' ],
					"body" : self._extract_body ( row [ 'body' ], txt ) } )

		cur.close ()

		return res

	def _extract_body ( self, body, txt ):
		import re


		# Remove HTML tags from text
		c = re.compile ( "<[^>]*>" )
		body = c.sub ( "", body )

		start = body.lower ().find ( txt.lower () )
		if start == -1: return body [ : 80 ]

		# Extract the exact string for highlight
		hl = re.compile ( "(" + re.escape ( txt ) + ")", re.I )

		start_pos = start - 30
		if start_pos < 0: start_pos = 0

		end_pos = start + len ( txt ) + 50

		extract = body [ start_pos : end_pos ]
		extract = hl.sub ( r"<strong>\1</strong>", extract )

		return extract
